<?php
    /**
     * Created by PhpStorm.
     * User: mybook-lhp
     * Date: 18/9/14
     * Time: 下午5:06
     */

    namespace app\store\api;


    use app\common\controller\API;

    use app\store\logic\DeliverGoodsLogic;
    use app\store\logic\OrderLogic;

    use app\store\logic\RefundLogic;
    use app\store\model\AddressModel;
    use app\store\model\CartModel;
    use app\store\model\LogisticsModel;
    use app\store\model\OrderInfoModel;
    use app\store\model\OrderModel;


    class Order extends API
    {

        /**
         * 单个商品下单
         * api POST /store/order/buyone
         *
         * @param string goods_id 商品ID
         * @param string goods_number 购买数量
         * @param int    address_id 收货地址
         * @param string remark 备注
         */
        public function buyone()
        {

            $data = $this->request->param();

            $this->check_validate($data,'Order.buyone');

            $data['buyer_id'] = $this->member_id;
            $order            = OrderLogic::buyone($data);
            if ($order['code'] == 200)
            {
                $this->success('下单成功','',['order_sn' => $order['data']['order_sn']]);
            }
            else
            {
                $this->error('下单失败');
            }
        }

        /**
         * 购物车商品下单
         * api POST /store/order/buycart
         *
         * @param        string    cart_ids 购物车列表ID
         * @param        int       address_id 收货地址
         * @param        string    remark 备注
         *
         * @param string $cart_ids 购物车ID(多个使用逗号分隔1，2，3，4)
         */
        public function buycart()
        {

            $data = $this->request->param();
            $this->check_validate($data,'Order.buycart');
            $data['buyer_id'] = $this->member_id;
            $order            = OrderLogic::buycart($data);
            if ($order['code'] == 200)
            {
                CartModel::whereIn('goods_id',$data['cart_ids'])->delete();
                $this->success('下单成功','',['order_sn' => $order['data']['order_sn']]);
            }
            else
            {
                $this->error($order['msg'],'',$data);
            }

        }

        /**
         * 购物车商品下单
         * api POST /store/order/get_order_buy_sn
         *
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         */
        public function get_order_buy_sn()
        {

            $data                = $this->check_validate_param('Order.get_order_buy_sn');
            $order               = OrderModel::where(['order_sn' => $data['order_sn']])->find();
            $order['order_info'] = OrderInfoModel::where(['order_sn' => $data['order_sn']])->select();
            $this->result($order);

        }

        /**
         * 下单购买
         * api POST /store/order/buyer
         */
        public function buyer()
        {

            $data             = $this->check_validate_param('Order.buyer');
            $data['buyer_id'] = $this->member_id;
            if (OrderLogic::buyer($data['order_sn'],$data['pay_type']))
            {
                $this->success('提交成功');
            }
            else
            {
                $this->success('提交失败');
            }
        }

        /**
         * 订单列表
         * api POST /store/order/order_lists
         *
         * @param int $list_rows 每页显示多少条数据
         * @param int $page      当前页数
         * @param int $status    状态(0:已取消10:未付款20:已付款21退款审核22退款成功23退款失败30:已发货40:已收货41:退货42:退货成功43退货失败)
         *
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         */
        public function order_lists()
        {

            $data  = $this->request->param();
            $where = ['buyer_id' => $this->member_id];
            if (isset($data['status']))
            {
                $where['status'] = $data['status'];
            }
            $list_rows = $data['list_rows'];
            unset($data['list_rows']);
            $OrderModel = OrderModel::where($where)//
            ->order('update_time','desc')//
            ->paginate($list_rows,false,['query' => request()->param()]);
            if ($OrderModel)
            {
                $data = $OrderModel->toArray();
                foreach ($data['data'] as &$item)
                {
                    $item['info'] = OrderInfoModel::where(['order_sn' => $item['order_sn']])->select();
                    foreach ($item['info'] as &$value)
                    {
                        $value['company_title'] = $value['goods_price'] . ' 积分/' . $value['goods_company'];
                        $value['goods_image']   = get_file_path($value['goods_image']);
                    }
                    unset($value);
                }
                unset($item);

                $this->result($data);
            }
            $this->result([]);
        }

        /**
         * 订单列表
         * api POST /store/order/order_details
         *
         * @param string order_sn 订单编号
         *
         * @throws \think\Exception
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         */
        public function order_details()
        {

            $data = $this->request->param();

            $OrderDetails = OrderModel::where(['buyer_id' => $this->member_id,'order_sn' => $data['order_sn']])->find();
            if ($OrderDetails)
            {
                $OrderDetails['msg']     = '';
                $OrderDetails            = $OrderDetails->toArray();
                $OrderDetails['address'] = json_decode($OrderDetails['address'],true);
                //                $OrderDetails['address'] = AddressModel::get($OrderDetails['address_id']);
                $OrderDetails['info'] = OrderInfoModel::where(['order_sn' => $OrderDetails['order_sn']])->select();
                foreach ($OrderDetails['info'] as &$value)
                {
                    $value['company_title'] = $value['goods_price'] . ' 积分/个';
                    $value['goods_image']   = get_file_path($value['goods_image']);
                }
                unset($value);
                if ($OrderDetails['status'] == 10)
                {
                    $OrderDetails['msg'] = '请在下单后一个两小时内付款，否则系统将自动取消此订单';
                }
                $OrderDetails['logistics'] = [
                    'express'        => LogisticsModel::field('code,company')->where('order_sn',$data['order_sn'])->find(),
                    'express_is_log' => false,
                    'express_log'    => [
                        ['收件'],
                        ['东莞到成都'],
                        ['收件高新区'],
                        ['已经签收'],
                    ]
                ];
                $this->result($OrderDetails);
            }
            $this->error('订单不存在');

            //            账号: 88160901402649@1256947
            //账号: 88160901402649@1256947
        }

        /**
         * 设置订单状态
         * api POST /store/order/order_status
         *
         * @param string order_sn  订单编号
         * @param int    status 订单状态
         *
         * @throws \think\Exception
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @throws \think\exception\PDOException
         */
        public function order_status()
        {

            $data = $this->check_validate_param('order.status');

            switch($data['status'])
            {
                case  OrderModel::STATUS_DELIVER_REFUND :
                    DeliverGoodsLogic::Apply($data['order_sn']) ? $this->success('操作成功！') : $this->error('操作失败');
                    break;

                case  OrderModel::STATUS_USER_REFUND:
                    RefundLogic::refund($data['order_sn']) ? $this->success('操作成功！') : $this->error('操作失败');
                    break;

                case  OrderModel::STATUS_DELIVER_SIGN:
                    OrderModel::update(['status' => OrderModel::STATUS_DELIVER_SIGN,'update_time' => time()],[
                        'order_sn' => $data['order_sn']
                    ]) ? $this->success('操作成功！') : $this->error('操作失败');
                    break;
                case  OrderModel::STATUS_CANCEL:
                    OrderModel::update([
                        'status'      => OrderModel::STATUS_CANCEL,
                        'update_time' => time()
                    ],['order_sn' => $data['order_sn']]) ? $this->success('操作成功！') : $this->error('操作失败');
                    break;

                default:
                    $this->error('操作失败');
            }
        }

        /**
         * 配置状态
         * api POST /store/order/config
         *
         * @return  array is_refund_money 是否退款
         * @return  array is_refund_goods 是否退货
         */
        public function config()
        {

            return [
                'is_refund_money' => false,
                'is_refund_goods' => false,
            ];
        }

    }